"""
CannyTrackbar function allows for a better understanding of
the mechanisms behind Canny Edge detection algorithm and rapid
prototyping. The example includes basic use case.

2 of the trackbars allow for tuning of the Canny function and
the other 2 help with understanding how basic filtering affects it.
"""
import cv2, os
# from base.settings import Settings
# from common.utils.utils import check_path
import numpy as np
from loguru import logger

blur_size = 0


def empty_function(*args):
    pass


def auto_canny(origin_img, image, sigma=0.33):
    # compute the median of the single channel pixel intensities
    v = np.median(origin_img)
    # apply automatic Canny edge detection using the computed median
    lower = int(max(0, (1.0 - sigma) * v))
    upper = int(min(255, (1.0 + sigma) * v))
    print('lower,upper', lower, upper)
    edged = cv2.Canny(image, lower, upper)
    # return the edged image
    return edged


def show_canny_trackbar(img, img_name=None):
    win_name = 'img_name'
    print(img_name)

    cv2.namedWindow(win_name)
    cv2.resizeWindow(win_name, 500, 100)

    cv2.createTrackbar("canny_th1", win_name, 60, 500, empty_function)
    cv2.createTrackbar("canny_th2", win_name, 152, 500, empty_function)
    cv2.createTrackbar("blur_size", win_name, 11, 255, empty_function)
    cv2.createTrackbar("blur_amp", win_name, 0, 255, empty_function)

    while True:
        cth1_pos = cv2.getTrackbarPos("canny_th1", win_name)
        cth2_pos = cv2.getTrackbarPos("canny_th2", win_name)
        bsize_pos = cv2.getTrackbarPos("blur_size", win_name)
        bamp_pos = cv2.getTrackbarPos("blur_amp", win_name)
        # bsize_pos = 11
        # bamp_pos = 0

        img_blurred = cv2.GaussianBlur(img.copy(), (bsize_pos * 2 + 1, bsize_pos * 2 + 1), bamp_pos)
        canny = cv2.Canny(img_blurred.copy(), cth1_pos, cth2_pos, L2gradient=True)
        # canny = auto_canny(img_blurred)
        result = cv2.resize(canny, (900, 900))
        img2 = cv2.resize(img, (900, 900))
        result = cv2.cvtColor(result, cv2.COLOR_GRAY2RGB)
        image = np.concatenate([result, img2], axis=1)
        cv2.imshow(win_name, image)
        key = cv2.waitKey(1) & 0xFF
        if key == ord("c"):
            break


def Canny(origin_img, img, img_name=None, bsize_pos=15, bamp_pos=0):
    img_blurred = cv2.GaussianBlur(img.copy(), (bsize_pos * 2 + 1, bsize_pos * 2 + 1), bamp_pos)
    # canny = cv2.Canny(img_blurred.copy(), cth1_pos, cth2_pos, L2gradient=True)
    canny = auto_canny(origin_img, img_blurred)
    return canny


# img = cv2.imread("static/first_load.jpg")
if __name__ == '__main__':
    # img_dir = Settings.TEST_IMG_PATH
    # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # BASE_DIR = '../../'
    BASE_DIR = '..'
    img_dir = BASE_DIR + '/resource/static/warmup/test_data/'
    # check_path(img_dir)
    index = 0
    while True:
        # 获取本地图片目录下的所有图片名称，然后随机read一张图片
        file_list = os.listdir(img_dir)
        if index < len(file_list) - 1:
            index += 1
        else:
            index = 0
            # import sys
            # sys.exit()
            # self.parent().stop_system()

        # index = random.randint(0, len(file_list) - 1)
        # img_temp = cv2.imread(Settings.BASE_DIR + '/static/{}.jpg'.format(index))
        filepath = img_dir + file_list[index]
        logger.debug(f"filepath:{filepath}")

        img_temp = cv2.imread(filepath)
        # img_temp = cv2.imread(img_dir + '/2001141647350.jpg')
        show_canny_trackbar(img_temp, file_list[index])
